/* eslint-disable*/
import type { ComputedRef } from 'vue';
import { BasicTableProps } from '/@/components/BasicTable/type/BasicTableProps';
import { EmitType } from '/#/index';
import { computed, onMounted, ref, toRaw, unref } from 'vue';
import { isFunction } from '/@/utils/is';

export function useDataSource(
  paramProps: ComputedRef<BasicTableProps>,
  paginationInfo: any,
  setPagination: any,
  getFieldsValue: any,
  emit: EmitType
) {
  const dataSourceRef = ref([]);
  const getDataSourceRef = computed(() => {
    return unref(dataSourceRef);
  });

  async function fetch() {
    const { api } = unref(paramProps);
    if (!api || !isFunction(api)) {
      return;
    }
    try {
      const { usePagination } = unref(paramProps);
      const { params } = unref(paramProps);
      let res: any;
      if (usePagination && usePagination === true) {
        const { current, size } = unref(paginationInfo);
        res = await api({
          ...params,
          ...getFieldsValue.getFieldsValue(),
          ...{ current, size },
        });
      } else {
        res = await api({
          ...params,
          ...getFieldsValue.getFieldsValue(),
        });
      }
      if (res.items) {
        dataSourceRef.value = res.items;
        setPagination({ total: res.total });
        emit('fetch-success', {
          items: unref(dataSourceRef),
          total: res.total,
        });
      } else {
        dataSourceRef.value = res;
        setPagination({ total: toRaw(dataSourceRef).value.length });
        emit('fetch-success', {
          items: unref(dataSourceRef),
          total: toRaw(dataSourceRef).value.length,
        });
      }
    } catch (error) {
      dataSourceRef.value = [];
      emit('fetch-error', error);
    }
  }

  async function handleTableChange(paginationInfo: any) {
    const { api, formConfig } = unref(paramProps);
    const { params } = unref(formConfig);
    const { current, size } = unref(paginationInfo);
    const res = await api({ ...params, ...{ current, size } });
    if (res.items) {
      dataSourceRef.value = res.items;
      setPagination({ total: res.total, current: res.current });
    } else {
      dataSourceRef.value = res;
      setPagination({ total: toRaw(dataSourceRef).value.length, current: res.current });
    }
  }

  function setTableData<T = Recordable>(values: T[]) {
    dataSourceRef.value = values;
  }

  function getDataSource<T = Recordable>() {
    return getDataSourceRef.value as T[];
  }

  async function reload() {
    return await fetch();
  }

  onMounted(() => {
    unref(paramProps).immediate && fetch();
  });
  return {
    fetch,
    reload,
    setTableData,
    getDataSource,
    handleTableChange,
    getDataSourceRef,
  };
}
